#include <QDebug>
#include <QHostAddress>
#include <QTcpSocket>
#include "widget.h"
#include "ui_widget.h"
#include<QString>

int balance=1000;//余额


Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    m_pServer= NULL;
    ui->lineEdit_2->setText(QString::number(balance));

}

Widget::~Widget()
{
    delete ui;

}

void Widget::InitWidget()
{
    qDebug()<<"void Widget::InitWidget() start";
    if(NULL!=m_pServer){
        return;
    }
    m_pServer=new QTcpServer(this);
    connect(m_pServer,SIGNAL(newConnection()),this,SLOT(OnNewConnection()));
    qDebug()<<"void Widget::InitWidget() end";
}

void Widget::StartConnect()
{
    qDebug()<<"void Widget::StartConnect() start";
    m_pServer->listen(QHostAddress("127.0.0.1"),8888);
    qDebug()<<"void Widget::StartConnect() end";
}

void Widget::OnNewConnection()
{
    qDebug()<<"void Widget::OnNewConnection() start";
    QTcpSocket *pSocket=m_pServer->nextPendingConnection();
    connect(pSocket,SIGNAL(readyRead()),this,SLOT(OnReadReady()));
            qDebug()<<"void Widget::OnNewConnection() end";
}

void Widget::OnReadReady()
{
    qDebug()<<"void Widget::OnReadReady() start";
    QTcpSocket *pSocket=(QTcpSocket *) sender();
    QByteArray arr=pSocket->readAll();
    qDebug()<< pSocket << " " <<arr;

    if(static_cast<char>(*arr.cbegin())==' '){
        ui->receiveData->setText(arr);
        QString string=QString::fromUtf8(arr);
        char c='=';
        int pos=string.indexOf(c);
        QString sumStr=string.mid(pos+1);
        int sum=sumStr.toInt();
        qDebug()<<"总价"+QString::number(sum);

        if(sum>balance){
            qDebug()<<"支付失败";

        }else{
            qDebug()<<"支付成功";

            balance=balance-sum;
            ui->lineEdit_2->setText(QString::number(balance));
        }
    }else{
        QString string=QString::fromUtf8(arr);
        bool ok;
        int number=string.toInt(&ok);
        qDebug()<<"余额"+number+ok;
        balance=number+balance;
        ui->lineEdit_2->setText(QString::number(balance));
        ui->lineEdit->setText(arr);
    }


    //QString str="send data to client"+arr;
    //pSocket->write(str.toStdString().data());

    qDebug()<<"void Widget::OnReadReady() end";
}



